import React, { Component, createRef } from 'react'
import PropTypes from 'prop-types'

export default class TodoInput extends Component {
    static propTypes = {
        btnText : PropTypes.string
    }

    static defaultProps = {
        btnText : '添加待办项'
    }

    // 构造函数只执行一次
    
    constructor(){
        super()

        this.state = {
            inputValue:''
        }

        //this重定向
        this.handleAddClick = this.handleAddClick.bind(this)
        this.handleKeyup = this.handleKeyup.bind(this)

        this.inputDom = createRef()
        
    }

    handleInputValue = (e)=>{
        
        this.setState({
            inputValue:e.currentTarget.value
        })
    }
    handleKeyup(e){
        if(e.keyCode===13){
            this.handleAddClick()
        }
    }

    handleAddClick(){
        if(this.state.inputValue === ''){
            return 
        }
        this.props.addTodo(this.state.inputValue)
        this.setState({
            inputValue:''
        },()=>{
            this.inputDom.current.focus()
        })
    }

    render(props) {
        return (
            <div>
                <input type="text" 
                value={this.state.inputValue}
                onChange = {this.handleInputValue}   
                onKeyUp = {this.handleKeyup}
                ref = {this.inputDom} 
            /> 
                <button onClick={this.handleAddClick}>{this.props.btnText}</button>
            </div>
        )
    }
}
